package application;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

import fetch.tilabdbplaces.ParserJson2Biz;
import data.Business;
import utils.config.Config;


public class MainParser {
	
	private String OUT_DB;
	private String BASE_DIR;
	
	public static void main(String[] args) throws Exception{
		
		MainParser mp = new MainParser();
		mp.parse();
		
		System.out.println("Done");
	}
	
	public MainParser(){
		Config config = new Config(this.getClass().getSimpleName()+".ser");
		
		OUT_DB = (String)config.get("OUT_DB");
		BASE_DIR = (String)config.get("BASE_DIR");
		
	}
	
	public void parse() throws Exception{
		
		ParserJson2Biz p = new ParserJson2Biz();
		
		File fdir = new File(BASE_DIR);
		File [] files = fdir.listFiles();
		
		Set<Business> biz = new HashSet<Business>();
		for(int i=0;i<files.length;i++){
			if(files[i].getName().endsWith(".json"))
				p.json2biz(files[i], biz);
			if(i%50 == 0)
				System.out.println(i+" out of "+files.length+" completed!");
		}
		
		Class.forName("com.mysql.jdbc.Driver").newInstance();
	    Connection c = DriverManager.getConnection(OUT_DB);
	    Statement s = c.createStatement();
	    
		for(Business b: biz) {
			String query = "INSERT INTO Business (name,address,category,city,subdivision,sizeLevel,activityLevel,checkins,coord) VALUES('"+b.name+"','"+b.address+"','"+b.category+"','"+b.city+"','"+b.subdivision+"','"+b.sizeLevel+"','"+b.activityLevel+"','"+b.checkins+"',GeomFromText('POINT("+b.lon+" "+b.lat+")'))";
			s.executeUpdate(query);
		}
		
		s.close();
	    c.close();
	    
	    System.out.println("Done");
		
	}

}
